package com.example.pagergallery

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.google.gson.Gson
import kotlin.math.ceil

const val DATA_STATUS_CAN_LOAD_MORE = 0
const val DATA_STATUS_NO_MORE = 1
const val DATA_STATUS_NETWORK_ERROR = 2
class GalleryViewModel(application: Application) : AndroidViewModel(application) {
    private val _dataStatusLive = MutableLiveData<Int>()  //监听当前数据的状态
    val dataStatusLive:LiveData<Int> get() = _dataStatusLive
    private val _photoListLive = MutableLiveData<List<PhotoItem>>()
    val photoListLive : LiveData<List<PhotoItem>>
    get() = _photoListLive

    private val keyWords = arrayOf("cat","dog","car","beauty","photo","computer","flower","animal","backgrounds", "fashion",
        "nature", "science", "education", "feelings", "health", "people", "religion", "places", "animals", "industry",
        "computer", "food", "sports", "transportation", "travel", "buildings", "business", "music","park","school","room",
        "sea","women","book","students","sky","landscape","technology","beauty","city","background","mid-autumn",
        "starry","architecture","forest","happy","birthday", "technology", "landscape", "starry sky","anime",
        "people", "moon", "illustration", "character", "cartoon","love","cute","belle","yellow","red","green","blue","pink",
        "gold","white","black","smoke","bridge","panda","bird","butterfly","forest","sun")
    var needToScrollToTop = true   //将UI滚动到最上面
    private var perPage = 50   //每页多少个图片
    private var currentPage = 1   //当前页面
    private var totalPage = 1   //总页面
    private var currentKey = "forest"   //当前关键词
    private var isNewQuery = true   //是否新的查询
    private var isLoading = false   //是否正在加载
    init{   //初始化，创建变量时就呼叫一次
        resetQuery()
    }

    fun resetQuery(){   //发起一次重新请求
        currentPage = 1
        totalPage = 1
        currentKey = keyWords.random()
        isNewQuery = true
        needToScrollToTop   //执行一次新的请求后就将UI滚动到最上面
        fetchData()
    }
    fun fetchData(){
        if (isLoading) return
        if (currentPage > totalPage) {
            _dataStatusLive.value = DATA_STATUS_NO_MORE
            return
        }
        isLoading = true
        val stringRequest = StringRequest(
            Request.Method.GET,
            getUrl(),
            Response.Listener {
                with(Gson().fromJson(it,Pixabay::class.java)){
                    totalPage = ceil(totalHits.toDouble() / perPage).toInt()    //ceil  向上取整
                    if (isNewQuery){
                        _photoListLive.value = hits.toList()
                    }else{
                        _photoListLive.value = arrayListOf(_photoListLive.value!!,hits.toList()).flatten()
                    }
                }
                _dataStatusLive.value = DATA_STATUS_CAN_LOAD_MORE
                isLoading = false
                isNewQuery = false
                currentPage++
            },
            Response.ErrorListener {
                _dataStatusLive.value = DATA_STATUS_NETWORK_ERROR
                isLoading = false
            }

        )
        VolleySingleton.getInstance(getApplication()).requestQueue.add(stringRequest)
    }

    private fun getUrl():String {
        return "https://pixabay.com/api/?key=28897448-3a1e9261edea4628f60ead645&q=${currentKey.random()}&per_page=${perPage}&page=${currentPage}"
    }




}